#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@File    ：exception_register.py
@Author  ：平
@Date    ：2025/9/28 10:57 
"""
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
from app.exception.exception import AuthorizationException
from app.register.abstract_register import AbstractRegister
from app.schema.base_response import BaseResponse
import logging

logger = logging.getLogger(__name__)


class ExceptionRegister(AbstractRegister):
    """
    异常注册类
    """

    def register(self, app: FastAPI):
        @app.exception_handler(Exception)
        async def exception_handler(request: Request, exc: Exception):
            logger.exception(f"{request.method} {request.url} 异常:{exc}")
            # 检查是否是AuthorizationException异常，如果是则交给专门的处理器处理
            if isinstance(exc, AuthorizationException):
                return await auth_exception_handler(request, exc)
            return JSONResponse(
                status_code=200,
                content=BaseResponse(code=500, message="服务器错误").model_dump()
            )

        async def auth_exception_handler(request: Request, exc: AuthorizationException):
            logger.exception(f"{request.method} {request.url} 异常:{exc}")
            return JSONResponse(
                status_code=200,
                content=BaseResponse(code=401, message="未授权").model_dump()
            )
